package 简单.长度为K子数组中的最大和;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author liugongding
 * @description:
 * @date 2024/9/6 10:59 PM
 */
public class Solution {
    public static long maximumSubarraySum(int[] nums, int k) {
        int maxSum = Integer.MIN_VALUE;
        int left = 0;
        int sum = 0;
        for (int right = 0; right < nums.length; right++) {
            int subLength = right - left + 1;
            sum += nums[right];
            if (subLength == k) {
                int indexSum= left == 0 ? 0 : nums[left - 1];
                sum = sum - indexSum;
                maxSum = Math.max(sum, maxSum);
                left++;
            }
        }
        return maxSum;
    }

    public static boolean containsDuplicateK(int[] nums, int k) {
        if (nums == null || nums.length < k || k <= 0) {
            return false;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);

            // 如果窗口大小超过了k，需要移除窗口最左边的元素
            if (i >= k && map.get(nums[i - k]) == 1) {
                map.remove(nums[i - k]);
            }
            // 检查窗口内是否有重复元素
            if (map.values().stream().anyMatch(count -> count > 1)) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] a = {1,5,4,2,9,1};
        System.out.println(maximumSubarraySum(a, 3));
        System.out.println(containsDuplicateK(a, 3));
    }
}
